package com.hjq.demo.ui.helpers;

import com.hjq.http.EasyLog;
import com.umeng.commonsdk.debug.E;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class MySocketClient {

    private Socket socket;
    private PrintWriter writer;
    private String url;
    private boolean turn;
    private int timeout = 800;
    public boolean isTurn() {
        return turn;
    }

    public String getUrl() {
        return url;
    }

    public boolean connect(String ip, int port) {
        try {
            this.url = String.format("%s", ip);
            SocketAddress endpoint = new InetSocketAddress(ip, port);
            socket = new Socket();
            socket.connect(endpoint, timeout);
            writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (Exception e) {
            EasyLog.print(e.getMessage());
            return false;
        }
        return true;
    }

    public boolean reconnect() {
        try {
            this.disconnect();
            SocketAddress endpoint = new InetSocketAddress(url, 80);
            socket = new Socket();
            socket.connect(endpoint, timeout);
            writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (Exception e) {
            EasyLog.print(e.getMessage());
            return false;
        }
        return true;
    }

    public boolean disconnect() {
        try {
            if (socket != null) {
                socket.close();
            }
            if (writer != null) {
                writer.close();
            }
        } catch (Exception e) {
            EasyLog.print(e.getMessage());
            return false;
        } finally {
            socket = null;
            writer = null;
        }
        return true;
    }

    public boolean send(String message) {
        boolean turnTemp = this.turn;
        try {
            if(this.socket == null || isConnected() == false){
                return false;
            }
            writer.println(message);
            if("G".equals(message)){
                this.turn = false;
            }else if("K".equals(message)){
                this.turn = true;
            }
        } catch (Exception e) {
            this.turn = turnTemp;
            EasyLog.print(e.getMessage());
            return false;
        }
        return true;
    }

    public String getStatus() {

        return String.format("%s,%s", this.url, socket != null ? socket.isConnected() : "false");
    }

    public boolean isConnected() {
        try {
            return socket.isConnected();
        }catch (Exception e){}
        return false;
    }
}
